package com.oem.fragment;

import static com.oem.fragment.contant.URLConstant.ORDER_URL;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


import com.oem.fragment.config.RetrofitClient;
import com.oem.fragment.model.Result;
import com.oem.fragment.model.order.CreateOrderDTO;
import com.oem.fragment.service.OrderService;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class OrderFragment extends Fragment {

    private EditText inputTitle, inputBudget, inputStartTime, inputEndTime, inputDescription;
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order, container, false);

        inputTitle = view.findViewById(R.id.inputTitle);
        inputBudget = view.findViewById(R.id.inputBudget);
        inputStartTime = view.findViewById(R.id.inputStartTime);
        inputEndTime = view.findViewById(R.id.inputEndTime);
        inputDescription = view.findViewById(R.id.inputDescription);
        Button btnSubmit = view.findViewById(R.id.btnSubmitOrder);

        bindDateTimePicker(inputStartTime);
        bindDateTimePicker(inputEndTime);

        btnSubmit.setOnClickListener(v -> submitOrder());

        return view;
    }

    private void bindDateTimePicker(EditText editText) {
        editText.setOnClickListener(v -> {
            Calendar calendar = Calendar.getInstance();
            new DatePickerDialog(requireContext(), (view, year, month, dayOfMonth) -> {
                new TimePickerDialog(requireContext(), (timeView, hour, minute) -> {
                    String result = String.format("%04d-%02d-%02dT%02d:%02d:%02d", year, month + 1, dayOfMonth, hour, minute, 0);
                    editText.setText(result);
                }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true).show();
            }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
        });
    }

    private void submitOrder() {
        String title = inputTitle.getText().toString().trim();
        String budgetStr = inputBudget.getText().toString().trim();
        String start = inputStartTime.getText().toString().trim();
        String end = inputEndTime.getText().toString().trim();
        String desc = inputDescription.getText().toString().trim();

//        if (title.isEmpty() || budgetStr.isEmpty() || start.isEmpty() || end.isEmpty()) {
//            Toast.makeText(requireContext(), "请填写完整的订单信息", Toast.LENGTH_SHORT).show();
//            return;
//        }

        start = "2024-12-30T00:00:00";
        end = "2025-01-05T23:59:59";
        budgetStr = "1001.0";
        title = "test tag title";

        try {
            BigDecimal budget = new BigDecimal(budgetStr);
            LocalDateTime startTime = LocalDateTime.parse(start, formatter);
            LocalDateTime endTime = LocalDateTime.parse(end, formatter);

            CreateOrderDTO.StrategyDTO strategy = new CreateOrderDTO.StrategyDTO(
                    "US,CA", "iOS,Android", "premium,loyal",
                    new BigDecimal("50.00"), 1000, 100);

            CreateOrderDTO dto = new CreateOrderDTO(
                    123L, budget, 1, startTime, endTime, desc, strategy);

            createOrder(dto);

        } catch (Exception e) {
            Toast.makeText(requireContext(), "数据格式错误：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void createOrder(CreateOrderDTO dto) {
        Retrofit retrofit = RetrofitClient.getClient(ORDER_URL);
        OrderService service = retrofit.create(OrderService.class);

        service.createOrder(dto).enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Result result = response.body();
                    if ("1".equals(result.getCode())) {
                        Toast.makeText(requireContext(), "订单创建成功，ID：" + result.getData(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(requireContext(), "订单失败：" + result.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(requireContext(), "请求失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                Toast.makeText(requireContext(), "网络异常: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
